﻿using System;
using UnityEngine;
using System.Collections.Generic;
public interface IClient
{
    void SendCmd(Cmd cmd);
    void ReceiveCmd(Cmd cmd);
}
public interface IServer 
{
    void Connect(IClient client);
    void SendCmd(Cmd cmd);
    void ReceiveCmd(Cmd cmd);
}

public class Client : BaseManager<Client>, IClient
{
    IServer _server;
    //消息类型 消息解析函数
    Dictionary<Type, Action<Cmd>> _parser = new Dictionary<Type, Action<Cmd>>();
    List<Cmd> _cache = new List<Cmd>();
    private bool _pause;
    public bool Pause { 
        get { return _pause; }
        set {
            _pause = value;
            if (value == false)
                ReceiveCmd(null);
        } }
    
    public Client()
    {
        _parser.Add(typeof(RoleListCmd), ClientCmdParser.OnRoleList);

        _parser.Add(typeof(EnterMapCmd), SceneMgr.OnEnterMap);
        _parser.Add(typeof(MainRoleThisIdCmd), RoleMgr.OnMainRoleThisID);
        _parser.Add(typeof(CreateSenceRoleCmd), RoleMgr.OnCreateSenceRoleCmd);
        _parser.Add(typeof(CreateSenceNpcCmd), NpcMgr.OnCreateSenceNpcCmd);
    }
    public void ServerConnect(Action successCallback, Action failCallback)
    {
        _server = Server.GetInstance();
        _server.Connect(this);
        if (true)
        {
            if (successCallback != null)
                successCallback();
        }
        else
        {
            if (failCallback != null)
                failCallback();
        }
    }
    public void SendCmd(Cmd cmd)
    {
        _server.ReceiveCmd(cmd);
    }

    public void ReceiveCmd(Cmd cmd)
    {
        //如果在阻塞状态，就不处理消息
        if (cmd != null)
        {
            _cache.Add(cmd);
        }
       
        if (Pause)
            return;
        //如果不在阻塞状体，就处理消息
        foreach (var cacheCmd in _cache)
        {
            Action<Cmd> func;
            if (_parser.TryGetValue(cacheCmd.GetType(), out func))
            {
                if (func != null)
                {
                    func(cacheCmd);
                }
            }
        }
        _cache.Clear();
    }
    public static bool CherkCmd(Cmd cmd,Type targetType)
    {
        if (cmd.GetType() != targetType)
        {
            Debug.LogError(string.Format("需要{0}，但收到{1}", targetType, cmd.GetType()));
            return false;
        }
        return true;
    }
}

